#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009 Vanderbilt University
# 
# Licensed under the Apache License, Version 2.0 (the "License"); 
# you may not use this file except in compliance with the License. 
# You may obtain a copy of the License at 
# 
#     http://www.apache.org/licenses/LICENSE-2.0 
# 
# Unless required by applicable law or agreed to in writing, software 
# distributed under the License is distributed on an "AS IS" BASIS, 
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
# See the License for the specific language governing permissions and 
# limitations under the License. 

"""Entry point for HORNET that launches the program. 

.. moduleauthor:: John Paulett <john.paulett -at- vanderbilt.edu>
"""

from hornet.application import PluginRunner, Config
from hornet.file import get_dir, join
from hornet.loading import load_class
from hornet.release import version
from optparse import OptionParser
import logging
import logging.config
import os

#import sys
#limit = sys.getrecursionlimit()
#sys.setrecursionlimit(limit*20)

def run(config_file):
    """Run HORNET."""
    config = load_class(config_file, Config)
    PluginRunner(config).run()
    
def profile():
    """Profile the main application."""
    import hotshot
    
    log = 'hotshot_network.log'

    prof = hotshot.Profile(log)
    prof.runcall(run)
    prof.close()
    
    logger.debug('Analyzing profile log: %s' % log)
    stats = hotshot.stats.load(log)
    stats.sort_stats('time').print_stats(30)
    
def _optparse():
    parser = OptionParser(version='%prog ' + version) #TODO fix the version
    parser.add_option('-a', '--action', dest='action', default='run',
                      help='Perform the ACTION (one of run, profile)', 
                      metavar='ACTION')
    parser.add_option('-c', '--config', dest='config', default='config_hornet.py',
                      help="""Use the configuration in CONFIG_FILE (defaults 
                      to './config_hornet.py')""", 
                      metavar='CONFIG_FILE')
    parser.add_option('-p', '--psyco', action='store_true', dest='enable_psyco', 
                      default=False, help='Turn on psyco compilation')

    (options, args) = parser.parse_args()
    return options, args

def main():
    logfile = join(get_dir(__file__), 'logging.conf')
    logging.config.fileConfig(logfile)
    logger = logging.getLogger(__name__)
    
    options, args = _optparse()
    if options.enable_psyco:
        import psyco
        psyco.full()

    action = options.action
    if action == 'run':
        run(options.config)
    elif action == 'profile':
        profile()
      
if __name__ == '__main__':
    main()